package com.fx.server.auth;

import com.fx.server.comm.FxJwtTool;
import com.fx.server.dto.FxUserDetail;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
@Component
public class FxJwtAuthenticationFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        FxUserDetail adminUserDetail = FxJwtTool.getUserFromToken(request);
        if(Objects.nonNull(adminUserDetail)){
            UsernamePasswordAuthenticationToken token =
                    new UsernamePasswordAuthenticationToken(adminUserDetail,null,adminUserDetail.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(token);
        }
        chain.doFilter(request,response);
    }
}
